package Controllers;

import Information.UserInfo;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.*;

import java.net.URL;
import java.time.LocalDate;
import java.util.ResourceBundle;

public class UserSiteController extends Application implements Initializable {
    private UserInfo userInfo;

    private String path;

    //设置性别的选项
    static ObservableList options =
            FXCollections.observableArrayList(
                    "男", "女", "不公开" );


    @FXML
    private DatePicker birthday;

    @FXML
    private Label UserId;

    @FXML
    private TextField ChangeName;

    @FXML
    private ComboBox<String> sex;

    @FXML
    private ImageView Avatar;


    @FXML
    private TextField oldPassword;//旧密码

    @FXML
    private TextField newPassword;//新密码

    @FXML
    private TextField newPasswordS;//再次确认新密码


    @FXML
    private AnchorPane UserInformationInterface; //个人信息界面
    @FXML
    private AnchorPane UserPasswordInterface; //修改密码界面


    private void getdate() {
        try (
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src/UserPosts/currentUser.ser")))
        {
            try {
                userInfo = (UserInfo) ois.readObject();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            //表现初始信息1
            path = userInfo.getAvatar();

            sex.getItems().addAll(options);
            sex.setValue(userInfo.getGender());             //设置性别

            Image image = new Image(userInfo.getAvatar());
            Avatar.setImage(image);                         //设置头像

            UserId.setText(userInfo.getId());               //设置id
            ChangeName.setText(userInfo.getPname());        //设置昵称

            if(userInfo.getBirthday() != null && !userInfo.getBirthday().equals("") && !userInfo.getBirthday().equals("null")){
            String[] a = userInfo.getBirthday().split("-");
            birthday.setValue(LocalDate.of(Integer.parseInt(a[0]),Integer.parseInt(a[1]),Integer.parseInt(a[2])));
            }                                  //设置出生日期
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {

        UserPasswordInterface.setVisible(false);
        getdate();
    }

    @Override
    public void start(Stage primaryStage) {
        try {
            AnchorPane root = FXMLLoader.load(getClass().getResource("../Resources/UserSite.fxml"));
            Scene scene = new Scene(root, 933.0, 625.0);
            //scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
            primaryStage.getIcons().add(new Image("/Images/logoblue.png"));
            primaryStage.setTitle("个人中心");
            primaryStage.setScene(scene);
            primaryStage.setResizable(false);
            primaryStage.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void openUserInformationInterface() {
        //切换个人信息界面
        UserPasswordInterface.setVisible(false);
        UserInformationInterface.setVisible(true);
    }
    public void openUserPasswordInterface() {
        //切换修改密码界面
        UserInformationInterface.setVisible(false);
        UserPasswordInterface.setVisible(true);
    }



    @FXML
    void ChangeAvatar() {
        //设置头像预览框
        try{
            Stage stage = null;
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("选择头像");
            fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))
            );
            fileChooser.getExtensionFilters().addAll(
                    new FileChooser.ExtensionFilter("JPG", "*.jpg"),
                    new FileChooser.ExtensionFilter("GIF", "*.gif"),
                    new FileChooser.ExtensionFilter("BMP", "*.bmp"),
                    new FileChooser.ExtensionFilter("PNG", "*.png")
            );
            File selectedFile =fileChooser.showOpenDialog(stage);
            path = selectedFile.getPath();}
        catch(Exception k){
            String info = "请选择文件，若找不到图片，可尝试改变搜索的图片类型";
            Alert alert = new Alert(Alert.AlertType.INFORMATION, info, new ButtonType("确定", ButtonBar.ButtonData.YES));
            alert.setHeaderText(null);
            alert.setTitle("提示");
            alert.show();
        }

        if(path.equals(userInfo.getAvatar())){
            Image image = new Image(path);
            Avatar.setImage(image);
        }else {
            Image image = new Image("file:" + path);
            Avatar.setImage(image);
            userInfo.setAvatar("file:"+path);
        }
    }

    @FXML
    void ChangeSchool(ActionEvent event) {
        String info = "该功能尚未实现";
        Alert alert = new Alert(Alert.AlertType.INFORMATION, info, new ButtonType("确定", ButtonBar.ButtonData.YES));
        alert.setHeaderText(null);
        alert.setTitle("提示");
        alert.show();
    }

    @FXML
    void Change(ActionEvent event) {
        //修改信息并插入对应userinfo.ser文件
        userInfo.setPname(ChangeName.getText());

        userInfo.setGender(sex.getValue());
        if(userInfo.getGender()==null) {
            String info = "请选择性别";
            Alert alert = new Alert(Alert.AlertType.INFORMATION, info, new ButtonType("确定", ButtonBar.ButtonData.YES));
            alert.setHeaderText(null);
            alert.setTitle("提示");
            alert.show();
        }

        try{
            userInfo.setBirthday(birthday.getValue().toString());
        }catch(Exception e){
            String info = "请选择日期";
            Alert alert = new Alert(Alert.AlertType.INFORMATION, info, new ButtonType("确定", ButtonBar.ButtonData.YES));
            alert.setHeaderText(null);
            alert.setTitle("提示");
            alert.show();
            return;
        }

        try(
                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("src/UserPosts/userObjects/"+ userInfo.getId()+".ser")))
        {   //写入当前对象
            oos.writeObject(userInfo);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try(
                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("src/UserPosts/currentUser.ser")))
        {   //写入当前对象
            oos.writeObject(userInfo);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String info = "修改成功";
        Alert alert = new Alert(Alert.AlertType.INFORMATION, info, new ButtonType("确定", ButtonBar.ButtonData.YES));
        alert.setHeaderText(null);
        alert.setTitle("提示");
        alert.show();
    }

    @FXML
    void changepassword(ActionEvent event) {
        String OldPassword = oldPassword.getText();
        String NewPassword1 = newPassword.getText();
        String NewPassword2 = newPasswordS.getText();//获取输入内容
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("src/Passwords/" + userInfo.getId() + ".txt"));
            String RealPassword = br.readLine();
            if (!OldPassword.equals(RealPassword)) {//比较原密码是否正确
                String info = "原密码输入错误，请重新输入";
                Alert alert = new Alert(Alert.AlertType.INFORMATION, info, new ButtonType("确定", ButtonBar.ButtonData.YES));
                alert.setHeaderText(null);
                alert.setTitle("提示");
                alert.show();
            } else if (!NewPassword1.equals(NewPassword2)) {//比较两次输入的旧密码
                String info = "新密码输入不同，请重新输入";
                Alert alert = new Alert(Alert.AlertType.INFORMATION, info, new ButtonType("确定", ButtonBar.ButtonData.YES));
                alert.setHeaderText(null);
                alert.setTitle("提示");
                alert.show();
            } else {
                //不确定标记，随时修改，此为具体修改密码的操作
                OutputStreamWriter ChangePassword;
                ChangePassword = new OutputStreamWriter(new FileOutputStream("src/Passwords/" + userInfo.getId() + ".txt"));
                ChangePassword.write(NewPassword1);
                try{
                    ChangePassword.close();
                }catch(IOException a){
                    a.printStackTrace();
                }
                String info = "修改成功";
                Alert alert = new Alert(Alert.AlertType.INFORMATION, info, new ButtonType("确定", ButtonBar.ButtonData.YES));
                alert.setHeaderText(null);
                alert.setTitle("提示");
                alert.show();
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally{
            if(br!=null){
                try{
                    br.close();
                }catch(IOException a){
                    a.printStackTrace();
                }
            }

        }


    }

}